package cc.owoo.godpen.network.http;

import java.util.HashMap;
import java.util.Map;

/**
 * Cookie
 * <p>
 * time 2021.03.23 03:06
 *
 * @author Fall
 */
public class Cookie extends HeaderProperty<Cookie> {
    private final HashMap<String, String> cookie = new HashMap<String, String>();// cookie值

    public Cookie() {
        super("cookie");
    }

    /**
     * 拷贝对象
     *
     * @param cookie 拷贝源
     */
    public void copySet(Cookie cookie) {
        this.cookie.clear();
        this.cookie.putAll(cookie.cookie);
    }

    @Override
    public boolean isEmpty() {
        return cookie.isEmpty();
    }

    @Override
    public String stringify() {
        StringBuilder string = new StringBuilder();
        for (Map.Entry<String, String> entry : cookie.entrySet()) {
            if (string.length() != 0)
                string.append("; ");
            string.append(entry.getKey()).append("=").append(entry.getValue());
        }
        return string.toString();
    }

    @Override
    public Cookie parse(String values) {
        for (String s : values.split(";")) {
            if (s == null || s.length() == 0)
                continue;
            int index = s.indexOf('=');
            if (index == -1)
                continue;
            String key = s.substring(0, index).trim();
            String value = s.substring(index + 1).trim();
            if (key.length() == 0 || value.length() == 0)
                continue;
            if (!key.equals("Path"))
                set(key, value);
        }
        return this;
    }

    @Override
    public void clear() {
        cookie.clear();
    }

    /**
     * 设置cookie属性
     *
     * @param key   键
     * @param value 值
     */
    public void set(String key, String value) {
        if (key == null || value == null || key.length() == 0 || value.length() == 0)
            return;
        cookie.put(key, value);
    }

    /**
     * 设置cookie
     *
     * @param cookie cookie对象
     */
    public void set(Cookie cookie) {
        cookie.clear();
        this.cookie.putAll(cookie.cookie);
    }

    /**
     * 添加cookie
     *
     * @param cookie cookie对象
     */
    public void append(Cookie cookie) {
        this.cookie.putAll(cookie.cookie);
    }

    /**
     * 将另一个cookie中的数据添加到该cookie中
     *
     * @param cookie cookie对象
     */
    public void addAll(Cookie cookie) {
        if (cookie == null)
            return;
        this.cookie.putAll(cookie.cookie);
    }

    @Override
    public String toString() {
        return stringify();
    }
}
